import { useState, useEffect } from 'react';
import { excelDataService } from '@/lib/excel-data-service';

export interface UseExcelDataReturn {
  // 各专业数据
  electricalData: any[];
  hvacData: any[];
  communicationData: any[];
  instrumentationData: any[];
  
  // 加载状态
  loading: boolean;
  error: Error | null;
  
  // 操作函数
  refetch: () => Promise<void>;
}

export function useExcelData(): UseExcelDataReturn {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const [electricalData, setElectricalData] = useState<any[]>([]);
  const [hvacData, setHvacData] = useState<any[]>([]);
  const [communicationData, setCommunicationData] = useState<any[]>([]);
  const [instrumentationData, setInstrumentationData] = useState<any[]>([]);

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);

      // 使用 parseExcelData 方法直接从服务器获取数据
      const filename = '06-06/0606-石楼油库实体对象与标准对比.xlsx';
      const data = await excelDataService.parseExcelData(filename);

      setElectricalData(data.electricalData);
      setHvacData(data.hvacData);
      setCommunicationData(data.communicationData);
      setInstrumentationData(data.instrumentationData);
    } catch (err) {
      console.error('数据加载失败:', err);
      setError(err instanceof Error ? err : new Error('数据加载失败'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return {
    electricalData,
    hvacData,
    communicationData,
    instrumentationData,
    loading,
    error,
    refetch: fetchData
  };
} 